package com.lzy.cloud.ticket.train.util;

import com.lzy.cloud.ticket.train.request.BaseRequest;
import com.lzy.cloud.ticket.train.request.InsuranceRequest;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;

/**
 * 基础实体类封装
 */
@Component
@PropertySource(value = "classpath:/props/train.properties")
public class BasePushUtil {

    @Value("${version}")
    private String version;
    @Value("${secert}")
    private String secret;

    public BaseRequest push(String appKey, String method, String messageFormt, String callBackUrl){
        BaseRequest baseRequest = new BaseRequest();
        baseRequest.setAppKey(appKey);
        baseRequest.setMethod(method);
        baseRequest.setMessageFormt(messageFormt);
        baseRequest.setCallbackUrl(callBackUrl);
        Long time = System.currentTimeMillis();
        baseRequest.setTimestamp(String.valueOf(time));
        baseRequest.setSign(MD5(secret+System.currentTimeMillis()+secret).toLowerCase());
        baseRequest.setVersion(version);
        return baseRequest;
    }

    private String MD5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes("utf-8"));
            return toHex(bytes);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i=0; i<bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

    /**
     * 获取坐席编码首字母小写
     * @param str
     * @return
     */
    public String getPinYinHeadChar(String str) {

        if(str.substring(str.length()-1).equals("铺")){
            str = str.substring(0,str.length()-1);
        }
        String convert = "";
        for (int j = 0; j < str.length(); j++)
        {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null)
            {
                convert += pinyinArray[0].charAt(0);
            } else
            {
                convert += word;
            }
        }
        return convert;
    }

}
